/**
 * copyright (c) by handpay 2012
 */
package com.handpay.framework.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import com.handpay.zztong.hp.R;

/**
 * 带有清空按钮的输入框
 *
 * @author：cqli
 * @date：2013-3-19 下午01:08:56
 */
public class HPEditText extends EditText {
    private int mButtonHeightPadding = 10;
    private int mButtonWidthPadding = 10;
    private ImageView btn;

    public HPEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        btn = new ImageView(getContext());
        btn.setBackgroundResource(R.drawable.btn_delete);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                HPEditText.this.setEnabled(true);
                HPEditText.this.setText("");

            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getY() > mButtonHeightPadding && event.getY() < getHeight() - mButtonHeightPadding &&
                event.getX() > getWidth() - mButtonWidthPadding - btn.getMeasuredWidth() && event.getX() < getWidth()) {
            HPEditText.this.setText("");
            HPEditText.this.setEnabled(true);
            return btn.dispatchTouchEvent(event);
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        btn.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(getMeasuredHeight() - mButtonHeightPadding * 2, MeasureSpec.EXACTLY));
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int size = btn.getMeasuredWidth() > btn.getMeasuredHeight() ? btn.getMeasuredHeight() : btn.getMeasuredWidth();
        btn.layout(0, 0, size, size);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (this.getText().toString().length() > 0) {
            canvas.save();
            int size = btn.getMeasuredWidth() > btn.getMeasuredHeight() ? btn.getMeasuredHeight() : btn.getMeasuredWidth();
            canvas.translate(getMeasuredWidth() - (size + mButtonWidthPadding), (getMeasuredHeight() - size) / 2);
            btn.draw(canvas);
            canvas.restore();
        }
    }
}
